package br.com.honorato.ejb;

import java.util.Arrays;
import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.interceptor.Interceptors;

import br.com.honorato.dao.UserAppDAO;
import br.com.honorato.enun.EUserAppStatus;
import br.com.honorato.enun.EYesNo;
import br.com.honorato.exception.DAOException;
import br.com.honorato.exception.EJBServiceException;
import br.com.honorato.exception.EncriptException;
import br.com.honorato.logger.Depurador;
import br.com.honorato.logger.InterceptorDeCallback;
import br.com.honorato.logger.LoggerInterceptor;
import br.com.honorato.model.UserApp;
import br.com.honorato.util.Hashing;
import br.com.honorato.util.PasswordUtil;

/**
 * Session Bean implementation class UserEJB
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@Interceptors(
{ Depurador.class, InterceptorDeCallback.class })
public class UserEJB extends BaseEJB
{
	// public static final String JNDI_NAME =
	// "java:module/UserEJB!br.com.honorato.ejb.UserEJB";

	public UserEJB()
	{}

	@LoggerInterceptor
	public List<UserApp> searchUsers()
	{
		return new UserAppDAO(getEm()).selectAll();
	}

	@LoggerInterceptor
	public UserApp saveUser(UserApp user) throws EJBServiceException
	{

		try
		{
			user = new UserAppDAO(getEm()).save(user);
			// TODO: enviar senha por email

		}
		catch (DAOException e)
		{
			/* TODO: RECUPERAR MENSAGEM DO BUNDLE */
			throw new EJBServiceException(e.getErrorCode(), e.getMessage());
		}

		return user;
	}

	@LoggerInterceptor
	public UserApp saveNewUser(UserApp user) throws EJBServiceException
	{

		user.setPassword(PasswordUtil.getRandomPasswordMD5(6));
		return saveUser(user);
		// TODO: enviar senha por email
	}

	@LoggerInterceptor
	public void deleteUser(UserApp user) throws EJBServiceException
	{

		try
		{
			user = getEm().find(UserApp.class, user.getIdUser());
			new UserAppDAO(getEm()).delete(user);

		}
		catch (DAOException e)
		{
			/* TODO: RECUPERAR MENSAGEM DO BUNDLE */
			throw new EJBServiceException(e.getErrorCode(), e.getMessage());
		}
	}

	@LoggerInterceptor
	public List<UserApp> searchUser(UserApp userFilter) throws EJBServiceException
	{
		// ArrayList<FilterQuery> filterList = new ArrayList<FilterQuery>();
		//
		// if (userFilter==null)
		// {
		// /*TODO: recuperar do bundle*/
		// throw new
		// EJBServiceException("CODIGO","filro de usuario nao informado");
		// }
		//
		// if (!"".equals(userFilter.getLogin()) && null!=userFilter.getLogin())
		// filterList.add(new EqualFilter("login",userFilter.getLogin()));
		//
		// if (!"".equals(userFilter.getName()) && null!=userFilter.getName())
		// filterList.add(new
		// LikeFilter(LikeFilter.BOTH,"name",userFilter.getName().toUpperCase()));
		//
		// if (userFilter.getStatus()!=null)
		// {
		// filterList.add(new EqualFilter("status",userFilter.getStatus()));
		// }
		//
		// try
		// {
		// return new UserAppDAO(getEm()).recoveryListByCriteria(filterList);
		// }
		// catch (DAOException e)
		// {
		// /*TODO: RECUPERAR MENSAGEM DO BUNDLE*/
		// throw new EJBServiceException(e.getErrorCode(), e.getMessage());
		// }
		return null;
	}

	public void changePassword(String login, String currentPassword, String newPassword, String newPasswordConfirmation) throws EJBServiceException
	{
		UserApp currentUser = getUserByLogin(login);

		if (currentUser == null)
		{
			/* TODO: RECUPERAR MENSAGEM DO BUNDLE */
			throw new EJBServiceException("changePassword", "Usuario nao encontrado para alteracao de senha!");

		}
		else if (!newPassword.equals(newPasswordConfirmation))
		{
			// TODO: recuperar do bundle e melhorar tratamento de erro
			FacesContext.getCurrentInstance().addMessage("", new FacesMessage("Redigitar senha corretamente"));

		}
		else
		{

			try
			{

				if (currentUser.getPassword().equals(Hashing.toMD5Hashing(currentPassword)))
				{

					currentUser.setPassword(Hashing.toMD5Hashing(newPassword));
					currentUser.setChangePassword(EYesNo.NO);
					saveUser(currentUser);

				}
				else
				{
					throw new EJBServiceException("changePassword", "Senha atual nao confere.");
				}
			}
			catch (EncriptException err)
			{
				throw new EJBServiceException(err.getErrorCode(), err.getMessage());
			}
		}
	}

	public List<EUserAppStatus> getUserStatusList() throws EJBServiceException
	{
		return Arrays.asList(EUserAppStatus.values());
	}

	@LoggerInterceptor
	public UserApp getUserByLogin(String login) throws EJBServiceException
	{
		try
		{
			return new UserAppDAO(getEm()).getBylogin(login);
		}
		catch (DAOException err)
		{
			throw new EJBServiceException(err.getErrorCode(), err.getMessage());
		}
	}
}